<template>
  <!-- 添加或修改菜单对话框 -->
  <el-dialog
    :title="!form.id ? '新增': '修改'"
    :visible.sync="visible"
    :close-on-click-modal=false
    v-dialogDrag
    append-to-body>
    <el-form ref="dataForm" :model="form" :rules="rules" label-width="80px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="工序类型" prop="parentId">
            <treeselect
              v-model="form.parentId"
              :options="menuOptions"
              :normalizer="normalizer"
              :show-count="true"
              placeholder="选择上级工序类型"
              noOptionsText="暂无数据"
              @input="handleParentIdChange"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item  label="类别" prop="processType">
            <el-radio-group v-model="form.processType" :disabled="flg" @change="updateRules">
              <el-radio-button label="0">工序类型</el-radio-button>
              <el-radio-button label="1">工序</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入工序/工序类别名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row  v-if="form.processType === '1'">
        <el-col :span="24">
          <el-form-item  label="所属工段" prop="workshopSection">
            <avue-select v-model="form.workshopSection" filterable clearable  dialogWidth="100%"   placeholder="请选择所属工段"  :props="{label: 'label',value: 'value'}"  :dic="workshopSectionList" ></avue-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="不良项目" v-if="form.processType === '1'">
        <el-input type="textarea" v-model="form.badItem"  placeholder="请输入不良项目" :autosize="{ minRows: 4}" />
      </el-form-item>
      <el-form-item label="报废项目" v-if="form.processType === '1'">
        <el-input type="textarea" v-model="form.scrapItem"  placeholder="请输入报废项目" :autosize="{ minRows: 4}" />
      </el-form-item>
        <el-form-item label="工序顺序" prop="sortOrder" v-if="form.processType === '1'">
          <el-input-number v-model="form.sortOrder" controls-position="right" :min="0" />
        </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="dataFormSubmit">确 定</el-button>
      <el-button @click="visible = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { fetchMenuTree, addObj, putObj, delObj ,getObj} from '@/api/pfoc/pfocprocess'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {remote} from "@/api/admin/dict";

export default {
  name: 'processForm',
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 菜单树选项
      menuOptions: [],
      // 是否显示弹出层
      visible: false,
      workshopSectionList:[],//工段集合
      // 查询参数
      queryParams: {
        processType: "0",
      },
      form: {
        id: undefined,//工序ID
        parentId: undefined,//父级ID
        name: null,//工序类名称
        processType: null,//类别
        workshopSection: null,//工段
        processName: null,//工序名
        sortOrder: undefined,//工序顺序
        badItem: "",//不良项目
        scrapItem: ""//报废项目
      },
      flg:false,//是否可选工序类别
      // 表单校验
      rules: {
        name: [
          {required: true, message: '工序/工序类型名称不能为空', trigger: 'blur'}
        ],
        processType:[
          {required: true, message: '请选择添加的类别', trigger: 'blur'}
        ],
        sortOrder: [
          {required: true, message: '工序顺序不能为空', trigger: 'blur'}
        ],
        workshopSection: [
          {required: true, message: '请选择所属工段', trigger: 'blur'}
        ],
        parentId: []
      }
    }
  },
  watch: {
    'form.parentId': function(newVal, oldVal) {
      // 判断当前是否是作业新增
      if(this.form.processType === '1' && this.validatenull(this.form.id)){
        //parentId不为-1且不为undefined，则表示当前是作业新增，需要判断是否为顶级节点，顶级节点需要设置parentId为-1
        if(this.form.parentId !== -1 && this.form.parentId  !== undefined){
          //获取当前选中节点下有多少数据
          this.form.sortOrder = this.countLeaves(this.menuOptions, this.form.parentId)+1;
        }
      }
    }
  },
  created() {
    //获取工段集合
    this.getWorkshopSectionListData();
  },
  methods: {
    init(isEdit, id , processType) {
      this.visible = true
      this.getTreeselect()
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.form.sortOrder = undefined
        this.form.parentId = id
        this.form.processType = processType
        this.flg = !this.validatenull(processType) && !this.validatenull(id);
        if (isEdit) {
          getObj(id).then(response => {
            this.form = Object.assign({}, this.form, Object.fromEntries(
              Object.entries(response.data.data).filter(([key]) => key in this.form)
            ));//防止为form新增属性，如createTime等，此方法只给form中存在的属性赋值
            if(this.form.processType==='1'){
              this.form.name = this.form.processName;
            }
          })
        } else {
          this.form.id = undefined
        }
      })
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          if (this.validatenull(this.form.parentId)) {
            this.form.parentId = -1
          }
          if(this.form.processType === '1'){
            this.form.processName = this.form.name;
            const selectedItem = this.findNodeById(this.menuOptions[0].children,this.form.parentId)
            this.form.name = selectedItem.label;
          }else{
            this.form.processName =null;
          }
          if (this.form.id) {
            putObj(this.form).then(data => {
              this.$message.success('修改成功')
              this.visible = false
              this.$emit('refreshDataList')
            })
          } else {
            addObj(this.form).then(data => {
              this.$message.success('添加成功')
              this.visible = false
              this.$emit('refreshDataList')
            })
          }
        }
      })
    },
    /** 查询菜单下拉树结构 */
    getTreeselect() {
       //创建对象
      fetchMenuTree().then(response => {
        this.menuOptions = []
        const menu = {id: -1, name: '根类', children: []}
        menu.children = response.data.data
        this.menuOptions.push(menu)
        // 判断当前是否是作业新增
        if(this.form.processType === '1' && this.validatenull(this.form.id)){
          //parentId不为-1且不为undefined，则表示当前是作业新增，需要判断是否为顶级节点，顶级节点需要设置parentId为-1
          if(this.form.parentId !== -1 && this.form.parentId  !== undefined){
            //获取当前选中节点下有多少数据
            this.form.sortOrder = this.countLeaves(this.menuOptions, this.form.parentId)+1;
          }
        }
      })
    },
    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      if(node.processType==='1'){
        return {
          id: node.id,
          label: null,
          children: node.children
        }
      }else {
        return {
          id: node.id,
          label: node.name,
          children: node.children
        }
      }
    },
    /** 动态更新表单校验规则 */
    updateRules() {
      if (this.form.processType === '1') {
        this.form.parentId = undefined;
        this.rules.parentId = [
          { validator: this.validateParentId, trigger: 'blur' }
        ]
      } else {
        this.rules.parentId = [];
         this.form.parentId = -1;
        this.form.workshopSection = null;
        this.form.badItem = "";
        this.form.scrapItem = "";
        this.form.sortOrder = undefined;
      }
      this.$refs['dataForm'].clearValidate('parentId')
    },
    /** 自定义校验规则 */
    validateParentId(rule, value, callback) {
      if (this.form.processType === '1' && (this.form.parentId === undefined || this.form.parentId === -1)) {
        callback(new Error('请选择有效的上级工序类型'))
      } else {
        callback()
      }
    },
    /** 在选择完符合产品类别的数据时重新校验 parentId */
    handleParentIdChange(value) {
      if (this.form.parentId !== undefined && this.form.parentId !== -1) {
        this.$refs['dataForm'].clearValidate('parentId')
      } else {
        this.$refs['dataForm'].validateField('parentId')
      }
    },
    //获取工段
    getWorkshopSectionListData(){
      remote("workshop_section").then(response => {
        this.workshopSectionList=response.data.data;
      })
    },
    //递归函数
    findNodeById(tree, id) {
      for (let node of tree) {
        if (node.id === id) {
          return node;
        }
        if (node.children && node.children.length > 0) {
          const foundNode = this.findNodeById(node.children, id);
          if (foundNode) {
            return foundNode;
          }
        }
      }
      return null;
    },
    // 获取当前选中节点下有多少数据
    countLeaves(options, selectedId) {
      let count = 0;
      function traverse(nodes) {
        nodes.forEach(node => {
          if (node.id === selectedId) {
            if (node.children) {
              node.children.forEach(child => {
                if (!child.children) {
                  count++;
                }
              });
            }
          } else if (node.children) {
            traverse(node.children);
          }
        });
      }
      traverse(options);
      return count;
    },

}
}
</script>
